
var evi= function(){}

var __dirname=process.cwd();

var HideMacMenu = function() {
	if (process.platform == "darwin") {
		var your_menu = new nw.Menu({
			type : 'menubar'
		});
		var submenu = new nw.Menu();
		your_menu.append(new nw.MenuItem({
			label : 'First Menu',
			submenu : submenu
		}));
		nw.Window.get().menu = your_menu;
	}
};
evi.prototype.ShowMobileForm = function(_type, Form, LandScapeVal) {
	var type = _type;
	var getClass = function(type) {
		var Css = "kmd-wrap " + type;
		if (type == "mobile-landscape" || type == "mobile" || type == "tablet-landscape" || type == "tablet") {
			return Css + "";
		} else {
			return Css
		}
	}
	Form.empty();

	var wrap = EVI.kamandaz_div({
		className : getClass(type)
	});
	var browser = EVI.span({
		className : "kmd-browser"
	});
	var span = EVI.span({ });
	var Panel = EVI.kamandaz_div({
		className : "wrap-Panel"
	});
	wrap.addChild(browser);
	browser.addChild(span);
	wrap.addChild(Panel);
	Form.addChild(wrap);
	this.Panel = Panel;
	if (type != 'mobile' && type != 'tablet') {
		var kmd_close = EVI.mini_i({
			className : "kmd-close"
		});
		var kmd_max = EVI.mini_i({
			className : "kmd-max"
		});
		var kmd_hide = EVI.mini_i({
			className : "kmd-hide"
		});
		span.addChild(kmd_close);
		span.addChild(kmd_max);
		span.addChild(kmd_hide);

		kmd_hide.addEventList("click", function() {
			var gui = require('nw.gui');
			var win = gui.Window.get();
			win.minimize();
		})
		kmd_close.addEventList("click", function() {
			var gui = require('nw.gui');
			var win = gui.Window.get();
			win.close();
		})
		window.maxoff = true;
		window._height = 768;
		window._width = 1024;
		kmd_max.onclick = browser.ondblclick = function() {
			var gui = require('nw.gui');
			var win = gui.Window.get();
			if (window.maxoff) {
				win.resizeTo(window._width, window._height)
				window.maxoff = false;
				kmd_max.className = "kmd-min";
			} else {
				kmd_max.className = "kmd-max";
				window._height = win.height;
				window._width = win.width;
				window.maxoff = true;
				win.maximize();
			}
		}
	} else {
		span.addEventList("mousedown", function(e) {
			if (e.button == 2) {
				var gui = require('nw.gui');
				var win = gui.Window.get();
				win.close();
			}
		})
	}

	var olde = null;
	var botton_ev = function(e) {
		var w = Form.Size();
		var h = w.height / 2;
		w = w.width / 2;
		if (e.offsetX > -56 && e.offsetX < -16 && h - 20 < e.offsetY && h + 20 > e.offsetY) {
			return 2;
		} else if (w + 5 > e.offsetX && w - 35 < e.offsetX && h * 2 - 105 > e.offsetY && h * 2 - 145 < e.offsetY) {
			return 1;
		} else {
			return 0
		}
	}
	/*wrap.onmousedown = function(e) {
	 var bool = botton_ev(e);
	 if (bool == 1 || bool == 2) {
	 window.close();
	 }
	 }*/
	browser.onmousedown = function(e) {
		var bool = 0;
		//botton_ev(e);
		if (bool == 0) {
			olde = e;
		} else if (bool == 1 || bool == 2) {
			window.close();
		}
	}
	browser.onmousemove = function(e) {
		if (olde != null) {
			var x = e.screenX - olde.clientX;
			var y = e.screenY - olde.clientY;
			var obj = {
				x : x,
				y : y
			};
			window.moveTo(obj.x, obj.y);
		}
	}
	browser.onmouseleave = function() {
		olde = null;
	}
	browser.mouseenter = function() {
		olde = null;
	}
	browser.onmouseup = function(e) {
		olde = null;
	}
	var _Landscape = function(off) {
		if (type == "mobile" || type == "tablet") {
			var Type = off ? type : type + "-landscape";
			wrap.className = getClass(Type)
		}
	}
	this.LandScape = _Landscape;
	this.SetMainClass = function(Type) {
		type = Type;
		wrap.className = getClass(Type)
	}
	LandScapeVal = LandScapeVal == null ? true : LandScapeVal;
	_Landscape(LandScapeVal);
}
/*
 evi.prototype.Nwexec = function(cmd, Close, Data) {
 var self = this;
 if (cmd) {
 Data = Data ? Data : function() {
 };
 Close = Close ? Close : function() {
 };
 var nwexec = require('child_process').exec, last = nwexec(cmd);
 last.stdout.on('data', function(data) {
 Data(data);
 });
 last.on('exit', function(code) {
 Close(code);
 });
 }
 }*/
/*
 @auhor	Musa
 @param	string url
 @param	function Callback
 * */
evi.prototype.getArgv = function() {
	var gui = require('nw.gui');
	var app = gui.App;
	var argv = app.argv;
	var Argv = {};
	for (var i = 0; i < argv.length; i++) {
		if (argv[i].indexOf("=") > 0) {
			var ps = argv[i].split("=");
			var name = ps[0];
			var value = ps[1];
			Argv[name.replace("-", "")] = value;
		}
	}
	return Argv;
}
evi.prototype.getSecureAddress = function(_fileName) {
	_fileName = _fileName.Replaces(":80/", "/");
	_fileName = _fileName.Replaces(":", "/");
	_fileName = _fileName.Replaces("//", "/");
	var ls = ["*", "?", '"', "<", ">", "|"];
	for (var i = 0; i < ls.length; i++) {
		_fileName = _fileName.Replaces(ls[i], "");
	};
	_fileName = _fileName + "";
	_fileName = _fileName.trim();
	return _fileName;
}
evi.prototype.getLocalImage = function(sourceUrl, Callback) {
	var url = EVI.getSecureAddress(encodeURI(sourceUrl.trim()));
	EVI.indexedDB.query("Base64Image", url, function(db) {
		Callback(db)
	})
}
/*
 @auhor	Musa
 @param	Image img
 @param	function Callback
 * */
evi.prototype.setLocalImage = function(img, Callback) {
	if (img == null || img.not_save_local) {
		return
	}
	var sourceUrl = img.src;
	if (img.org_src) {
		sourceUrl = img.org_src;
	}
	var key = EVI.getSecureAddress(encodeURI(sourceUrl.trim()));
	function getBase64Image(image, ext) {
		var canvas = document.createElement("canvas");
		var width = image.width;
		if (image.org_width) {
			width = image.org_width;
		}
		var height = image.height;
		if (image.org_height) {
			height = image.org_height;
		}
		canvas.width = width;
		canvas.height = height;
		var context = canvas.getContext("2d");
		context.drawImage(image, 0, 0, image.width, image.height);
		var base64 = canvas.toDataURL("image/png");
		return base64;
	}

	var Base64 = getBase64Image(img, 'png');
	EVI.indexedDB.Add("Base64Image", {
		url : key,
		img : Base64
	})
}
/*
 @auhor	Musa
 @param	object obj
 @param	Array item
 @param	function Callback
 * */
evi.prototype.nwTray = function(obj, item, Callback) {
	var isShowWindow = true;
	// Load native UI library
	var gui = require('nw.gui');
	var win = gui.Window.get();
	var tray = new gui.Tray({
		title : obj.title,
		icon : obj.icon/// 'static/image/marker.png'
	});
	if (o.tooltip) {
		tray.tooltip = o.tooltip;
	}
	if (item) {
		var menu = new gui.Menu();
		for (var i = 0; i < item.length; i++) {
			menu.append(new gui.MenuItem({
				type : item[i].type,
				label : item[i].label
			}));
		};
		tray.menu = menu;
	}
	menu.append(new gui.MenuItem({
		type : 'checkbox',
		label : '选择我'
	}));
	tray.on('click', function(o) {
		Callback(o);
	});
}
/*
 @auhor	Musa
 @param	string src
 @param	string dst
 * */
evi.prototype.Nwcopy = function(src, dst) {
	var fs = require("fs");
	readable = fs.createReadStream(src);
	// 创建写入流
	writable = fs.createWriteStream(dst);

	readable.pipe(writable);
}
/*
 @auhor	Musa
 @return require('nw.gui').Shell
 * */
evi.prototype.nwShell = function() {
	var gui = require('nw.gui');
	var shell = gui.Shell;
	return shell
}
/*
 @auhor	Musa
 @param	string cmd
 @param	function Close
 @param	function Data
 * */
evi.prototype.Nwexec = function(cmd, Close, Data) {
	if (cmd) {
		Data = Data ? Data : function() {
		};
		Close = Close ? Close : function() {
		};
		var nwexec = require('child_process').exec, last = nwexec(cmd);
		last.stdout.on('data', function(data) {
			Data(data);
		});
		last.on('exit', function(code) {
			Close(code);
		});
	}
};
/*
 @auhor	Musa
 @param	string file
 @param	function Callback
 * */
var tojsondb = function(str) {
	str = str.trim();
	if (str[0] == "{" || str[0] == "[") {
		var db = {};
		try {
			db = JSON.parse(str);
		} catch(err) {
			db = null;
		}finally {
			
			
		}
		return db;
	} else {
		str = str.substr(1, str.length)
		return tojsondb(str.trim());
	}
}
evi.prototype.OpenJson = function(file, Callback) {
	var fs = require("fs");
	fs.exists(file, function(exists) {
		if (exists) {
			var model = EVI.Open_File(file, 'utf-8');
 
			 
			model = tojsondb(model);
			Callback(model)
		} else {
			Callback(null);
		}
	});
}
/*
 @auhor	Musa
 @param	string file
 @param	string value
 @param	function callback
 * */
evi.prototype.SaveJson = function(file, value, callback) {
	var str = JSON.stringify(value);
	EVI.Save_File(file, str, null, callback);
}
/*
 @auhor	Musa
 @param	string file
 @return	string User File+file
 * */
evi.prototype.getUserFile = function(file) {
	var UserFile = "";
	if (process.platform == "win32") {
		UserFile = process.env.USERPROFILE;
	} else {
		UserFile = process.env.HOME;
	}
	if (file == null) {
		return UserFile
	} else {
		return EVI.toSystemPath(UserFile + file);
	}
}
/*
 @auhor	Musa
 @param	string url
 @param	object options
 @param function callback require("nw.gui").Window.open
 * */
evi.prototype.NWwindow = function(url, options, callback) {
	var gui = require("nw.gui");
	if (parseFloat(process.version.replace("v", "")) >= 5.12 && options && options.toolbar != undefined) {
		delete options.toolbar;
	};

	var win = gui.Window.open(url, options, callback);
	if (process.version == "v1.2.0") {
		var time = setInterval(function() {
			if (win.window) {
				clearInterval(time);
				callback(win);
			}
		}, 500);
	}
};
/*
 @auhor	Musa
 @param	string url
 @param	object data
 @param function callback
 * */
evi.prototype.NWPost = function(url, data, callback) {
	function getHost(url) {
		var host = "null";
		if ( typeof url == "undefined" || null == url) {
			url = window.location.href;
		}
		var regex = /^\w+\:\/\/([^\/]*).*/;
		var match = url.match(regex);
		if ( typeof match != "undefined" && null != match) {
			host = match[1];
		}
		return host;
	};
	var db = require('querystring').stringify(data);
	var host = getHost(url);
	path = url.split(host);
	var ht = path[0];
	var opt = {
		method : "POST",
		host : host,
		path : path[1],
		headers : {
			"Content-Type" : 'application/x-www-form-urlencoded',
			"Content-Length" : db.length
		}
	};
	var complete = false;
	var http;
	if (ht == "https") {
		http = require('https');
	} else {
		http = require('http');
	}
	var _Complete = function(db) {
		if (!complete) {
			complete = true;
			callback(db)
		}
	}
	var http = require('http');
	var req = http.request(opt, function(res) {
		if (res.statusCode == 200) {
			var body = "";
			res.on('data', function(data) {
				body += data;
			}).on('end', function() {
				_Complete(body);
			}).on('error', function(e) {
				_Complete(null);
			});
		}
	});
	setTimeout(function() {
		req.abort();
		_Complete(null);
	}, 20000);
	req.write(db + "\n");
	req.end();
};

/*
 @auhor	Musa
 * */
evi.prototype.NWclose = function() {
	var gui = require('nw.gui');
	var win = gui.Window.get();
	win.close();
}

evi.prototype.evalNWBin = function(bin) {
	var gui = require("nw.gui");
	gui.Window.get().evalNWBin(null, bin);
}
evi.prototype.OpenNewApp = function(Path, cf, Callback) {
	var f = process.platform;
	var appfile = "";
	if (f == "linux") {
		appfile = Path;
	} else if (f == "win32") {
		appfile = "start " + Path + ".exe";
	} else {
		appfile = "open " + (Path + ".app --args");
	}
	var cmd = appfile;
	if (cf != false) {
		cmd = appfile + " " + cf;
	};
	new EVI.Nwexec(cmd, function(id) {
		if (id == 0 || id == "0") {
			Callback(id);
		} else {
			Callback("error");
		};
	}, function(a) {
		Callback(a);
	});
};
/*
 @auhor	Musa
 @param	string Path
 @param	object cf
 @param function Callback
 * */
evi.prototype.OpenApp = function(Path, cf, Callback) {
	var nwDir = EVI.getDirname(process.execPath);
	nwDir = nwDir.split("nw.app")[0];
	var f = process.platform;
	var appfile = "";
	if (f == "linux") {
		appfile = nwDir + "/" + Path
	} else if (f == "win32") {
		Path = '\\' + Path;
		appfile = "start " + nwDir + Path + ".exe";
	} else {
		appfile = "open " + nwDir + (Path + ".app --args");
	}
	appfile = EVI.toSystemPath(appfile);
	var cmd = appfile;
	if (cf != false) {
		cmd = appfile + " " + cf;
	};
	new EVI.Nwexec(cmd, function(id) {
		if (id == 0 || id == "0") {
			Callback(id);
		} else {
			Callback("error");
		};
	}, function(a) {
		Callback(a);
	});
};
var Printwin = function(db) {
	var height = db.height;
	var width = db.width;
	var cf = {
		"icon" : "plug/icon/printer.png",
		title : "Print",
		position : 'center',
		resizable : false,
		fullscreen : false,
		width : width,
		height : height,
		focus : true
	};
	if (process.version == "v1.2.0") {
		cf["toolbar"] = false;
	}
	new EVI.NWwindow("plug/printer.html", cf, function(_win) {
		var pwin = _win;
		var time = setInterval(function() {
			var dc = ("docu" + "ment");
			if (pwin && pwin.window && pwin.window[dc] && pwin.window[dc].getElementById("kmd")) {
				clearInterval(time);
				var dg = new EVI.Drawgrid(pwin.window[("docu" + "ment")].getElementById("kmd"), db);
				pwin.window.print();
				pwin.window.close();
			}
		}, 500);
	});
};
evi.prototype.webPrint = Printwin;
window.webPrint = Printwin;
evi.prototype.Update_application_configuration = function(new_flie, lod_file, stop_name, Callback) {
	var f = process.platform == "win32" ? 1 : 2;
	if (f == 1) {
		var nwDir = EVI.getDirname(process.execPath);
		var cmd = 'taskkill /im ' + stop_name + '.exe /f';
		new EVI.Nwexec(cmd, function() {
			var cmd = 'xcopy  /e /y ' + nwDir + new_flie + ' ' + nwDir + lod_file;
			new EVI.Nwexec(cmd, function() {
				Callback()
			}, function() {
				Callback();
			});
		});
	};
}
/*
 @auhor	Musa
 @param	string DirPath
 * */
evi.prototype.NWmkdirs = function(DirPath) {
	var fs = require("fs");
	if (!fs.existsSync(DirPath)) {
		var f = process.platform == "win32" ? 1 : process.platform == "linux" ? 3 : 2;
		var keys = '/';
		if (f == 1) {
			keys = '\\'
		};
		var ls = DirPath.split(keys);
		DirPath = ls[0];
		for (var i = 1; i < ls.length; i++) {
			DirPath = DirPath + keys + ls[i];
			if (!fs.existsSync(DirPath)) {
				fs.mkdirSync(DirPath);
			}
		};
	}
};
evi.prototype.get_app_file = function(Path) {
	Path = Path == null ? "" : Path;
	var path = require('path');
	var nwDir = path.dirname(process.execPath);
	nwDir = nwDir.split("nw.app")[0];
	var f = process.platform == "win32" ? 1 : process.platform == "linux" ? 3 : 2;
	var file = "";
	if (f == 2) {
		file = nwDir + Path;
	} else {
		file = nwDir + "/" + Path
	}
	file = EVI.toSystemPath(file);
	return file;
}

evi.prototype.getDirname = function(Path) {
	var path = require('path');
	var nwDir = path.dirname(Path);
	return nwDir
}
evi.prototype.getParentPath = function(Path, elm) {
	if (elm == null) {
		if (process.platform == "win32") {
			elm = '\\'
		} else {
			elm = '/';
		}
	}
	var db = Path.split(elm);
	db[db.length - 1] = "";
	return db.join(elm);
}
evi.prototype.toSystemPath = function(Path) {
	var f = process.platform == "win32" ? 1 : process.platform == "linux" ? 3 : 2;
	if (f == 1) {
		Path = Path.replace(/\//g, "\\");
	} else {
		Path = Path.Replaces('\\', '/');
	}
	return Path + '';
}
evi.prototype.deleteFolderRecursive = function(path) {
	var fs = require("fs");
	var files = [];

	if (fs.existsSync(path)) {

		files = fs.readdirSync(path);

		files.forEach(function(file, index) {

			var curPath = path + "/" + file;

			if (fs.statSync(curPath).isDirectory()) {// recurse

				EVI.deleteFolderRecursive(curPath);

			} else {// delete file

				fs.unlinkSync(curPath);

			}

		});
		fs.rmdirSync(path);
	}

};

/*
 @auhor	Musa
 @param	string url
 @param	string Path
 @param function Callback
 @param function progress
 * */
evi.prototype.Download = function(url, Path, callback, progress) {
	var fs = require("fs");
	Path = EVI.toSystemPath(Path);
	EVI.NWmkdirs(EVI.getDirname(Path));
	var http = require("http");
	callback = callback == null ? function() {
	} : callback;
	http.get(url, function(res) {
		var imgData = "";
		res.setEncoding("binary");
		res.on('progress', function(bytesReceived, bytesExpected) {
			if (progress != null && progress.SetValue) {
				progress.SetValue(bytesReceived / bytesExpected * 100);
			}
		});
		res.on("data", function(chunk) {
			imgData += chunk;
		});
		res.on("end", function() {
			fs.writeFile(Path, imgData, "binary", function(err) {
				if (err) {
					callback(err)
				} else {
					callback(err)
				}
			});
		});
	});
}
/*
 @auhor	Musa
 @param	string path
 * */
evi.prototype.Open_File = function(path) {
	var fs = require('fs');
	path = EVI.toSystemPath(path);
	var Content = fs.readFileSync(path, 'utf-8');
	return Content;
}
/*
 @auhor	Musa
 @param	string file
 @param	string value
 @param object encoding
 @param function callback
 * */
evi.prototype.Save_File = function(file, value, encoding, callback) {
	callback = callback == null ? function() {
	} : callback;
	file = EVI.toSystemPath(file);
	EVI.NWmkdirs(EVI.getDirname(file));
	encoding = encoding == null ? 'utf-8' : encoding;
	var fs = require('fs');
	fs.writeFile(file, value, {
		encoding : encoding
	}, callback);
}

evi.prototype.List_Folders = function(path, callback) {
	var fileList = [];
	try {

		var self = this;
		var fs = require('fs');
		var walk = function(path) {
			var dirList = fs.readdirSync(path);
			dirList.forEach(function(item) {
				var dbf = EVI.toSystemPath(path + '\\' + item)
				if (fs.statSync(dbf).isDirectory()) {
					walk(dbf);
				} else {
					if ( typeof (callback) == "function") {
						callback(dbf, item);
					}
					fileList.push(dbf);
				}
			});
		}
		walk(EVI.toSystemPath(path));
	} catch(error) {
	};
	return fileList
}
function IndexedDB(config) {
	var init = function(cf) {
		var version = cf.version || 1;
		var request = window.indexedDB.open(cf.name, version);
		request.onerror = function(e) {
			console.log(e.currentTarget.error.message);
		};
		request.onupgradeneeded = function(e) {
			/// console.log('DB version changed to '+version);
			var db = e.target.result;
			for (var i = 0; i < cf.dbls.length; i++) {
				newobj(e.target.result, cf.dbls[i]);
			};
		};
		request.onsuccess = function(e) {
			cf.db = e.target.result;
		};
	}
	var newobj = function(db, obj) {
		if (obj == null || db == null) {
			return
		}
		if (!db.objectStoreNames.contains(obj.storeName)) {
			db.createObjectStore(obj.storeName, {
				keyPath : obj.key
			});
		}
	}
	this.Add = function(storeName, info) {
		var db = config.db;
		if (db == null) {
			return
		}
		newobj(db, get_key(storeName, true));
		var key = get_key(storeName);
		if (key != null) {
			self.query(storeName, info[key], function(db, Store) {
				if (db == null) {
					Store.add(info);
				} else {
					for (var key in info) {
						db[key] = info[key];
					};
					Store.put(db)
				}
			})
		}
	}
	var get_key = function(storeName, off) {
		var ls = config.dbls;
		for (var sk = 0; sk < ls.length; sk++) {
			if (ls[sk].storeName == storeName) {
				if (off) {
					return ls[sk]
				} else {
					return ls[sk].key
				}
			}

		};
		return null;
	}
	this.Adds = function(storeName, infos) {
		for (var i = 0; i < infos.length; i++) {
			this.Add(infos[i]);
		};
	}
	this.query = function(storeName, key, callback) {
		var db = config.db;
		if (db == null) {
			callback(null)
			return
		}
		newobj(db, get_key(storeName, true));
		var transaction = db.transaction(storeName, 'readwrite');
		var store = transaction.objectStore(storeName);
		var request = store.get(key);
		request.onsuccess = function(e) {
			var student = e.target.result;
			callback(student, store)
		};
	}
	init(config);
	var self = this;
}

evi.prototype.StatrtPrinter = function(obj, Callback) {
	var f = process.platform == "win32" ? 1 : 2;
	if (f == 1) {
		var p = "";
		for (var key in obj) {
			p = p + " --" + key + "=" + obj[key];
		}
		var appfile = EVI.get_app_file("Perinter.exe");
		var cmd = appfile + p;
		new EVI.Nwexec(cmd, function(id) {
			Callback(id),
			function(value) {
				Callback(value)
			}

		})
	};
}
evi.prototype.getPrinterList = function(Callback) {
	if (process.platform == "win32") {
		var appfile = EVI.get_app_file("Perinter.exe");
		var cmd = appfile + " --list=yes";
		new EVI.Nwexec(cmd, function(id) {

		}, function(a) {
			var db = [];
			try {
				var db = tojsondb(a);
			} catch(e) {
				db = [];
			}
			for (var i = 0; i < db.length; i++) {
				db[i] = {
					"text" : db[i],
					"id" : db[i]
				}
			};
			Callback(db)
		})
	} else {
		Callback(null)
	}
}
evi.prototype.indexedDB = new IndexedDB({
	name : 'kmd_db',
	version : 23,
	db : null,
	dbls : [{
		storeName : "Base64Image",
		coment : ["url", 'img'],
		key : "url"
	}, {
		storeName : "webjsondb",
		coment : ["url", 'json'],
		key : "url"
	}]
});
HideMacMenu();
